const schedule = require('node-schedule');
const comment = require('../db/collection/comment');
const article = require('../db/collection/article');
const request = require('request');
const site = require('../config/config').site;
const subscribe = require('../config/config').subscribe;
const sendMsg = require('./sendMsg');
var log = require('./log');

// 获取子评论
function getChildren(comment, id) {
	let children = comment.children;
	// 有回复
	if (children != null) {
		for (let i = 0; i < children.length; i++) {
			const element = children[i];
			if (element.parentId == id) {
				return element;
			} else {
				return getChildren(element, id);
			}
		}
	} else {
		// 无回复
		return null;
	}
}

// 时间转换
function time2Date(timestamp) {
	let date = new Date(timestamp);
	let Y = date.getFullYear();
	let M = (date.getMonth() + 1 < 10) ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
	let D = (date.getDate() < 10) ? '0' + date.getDate() : date.getDate();
	let h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
	let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
	let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
	return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}

// 留言推送
function pushComment() {
	return new Promise((resolve, reject) => {
		comment.find().then(res => {
			if (res.length) {
				for (let i = 0; i < res.length; i++) {
					if (res[i].subscribeTimes <= 0) {
						continue;
					}
					// 公共数据
					let publicData = {
						title: res[i].title,
						content: res[i].content,
						articleId: res[i].articleId
					}

					// 获取某文章下某条评论的子评论接口
					let api = site.url + `/api/content/posts/${res[i].articleId}/comments/${res[i].commentId}/children`;

					request({
						url: api,
						headers: {
							'API-Authorization': site.key
						}
					}, (err, response, body) => {
						if (err) {
							log.getLogger('errors').error(err);
							reject(false);
						}
						if (response.statusCode != 200) {
							return false;
						}
						let data = JSON.parse(body);
						if (data.status != 200) {
							return false;
						}
						let content = data.data;
						if (!content) {
							return false;
						}
						for (let j = 0; j < content.length; j++) {
							let element = content[j];
							if (element.parentId == res[i].commentId) {
								// 组装数据
								let postData = {
									"touser": res[i].openId,
									"template_id": subscribe.comment,
									"page": "pages/details/index?id=" + publicData.articleId,
									"lang": "zh_CN",
									"data": {
										"thing1": {
											"value": publicData.content,
										},
										"thing2": {
											"value": element.content,
										},
										"thing3": {
											"value": "评论有回复啦！",
										},
										"name4": {
											"value": element.author,
										},
										"thing5": {
											"value": publicData.title,
										}
									}
								};
								comment.deleteOne({ "commentId": res[i].commentId }, (err) => {
									if (err) {
										log.getLogger('errors').error(err);
										reject(false);
									} else {
										sendMsg(postData).then(ret => {
											log.getLogger('app').info("评论消息推送成功");
											resolve(true);
										})
									}
								});
							}
						}
					})
				}
			} else {
				resolve(true);
			}
		})
	});

}

// 新文章推送
function pushArticle() {
	return new Promise((resolve, reject) => {
		// 获取每天开始的时间
		let daySart = new Date(new Date().toLocaleDateString()).getTime();
		request({
			url: site.url + "/api/content/posts",
			headers: {
				'API-Authorization': site.key
			}
		}, (err, response, body) => {
			if (err) {
				log.getLogger('errors').error(err);
			}
			if (response.statusCode != 200) {
				return false;
			}
			let data = JSON.parse(body);
			let content = data.data.content;

			if (!content.length) {
				return false;
			}

			// 今天内所有的新文章
			let pushArticleData = new Array();

			// 导出一天内所有的新文章
			for (let i = 0; i < content.length; i++) {
				const element = content[i];
				// 今天发布了新文章
				if (element.createTime > daySart) {
					pushArticleData.push({
						"touser": "",
						"template_id": subscribe.article,
						"page": "pages/details/index?id=" + element.id,
						"lang": "zh_CN",
						"data": {
							"thing1": {
								"value": element.title.substr(0, 20),
							},
							"time2": {
								"value": time2Date(element.createTime),
							},
							"name3": {
								"value": site.author,
							}
						}
					})
				}
			}

			article.find({ subscribeTimes: { $gt: 0 } }).then(doc => {
				if (doc.length) {
					// 遍历订阅过的用户
					for (let i = 0; i < doc.length; i++) {
						let times = doc[i].subscribeTimes;
						// 当天新文章总数与该用户订阅次数不一致，取小
						let total = pushArticleData.length > times ? times : pushArticleData.length;
						// 将要推送的数据发送给每一位用户
						for (let j = 0; j < total; j++) {
							let ArticleDataEle = pushArticleData[j];
							ArticleDataEle['touser'] = doc[i].openId;
							if (times > 0) {
								sendMsg(ArticleDataEle).then(rest => {
									console.log(ArticleDataEle);
									// 发送成功减一操作
									if (rest && rest == 'OK') {
										times -= 1;
										article.updateOne({ openId: doc[i].openId }, { subscribeTimes: times }).then(res => {
											log.getLogger('app').info('新文章推送成功')
										})
									}
								}, err => {
									console.log("出错：", ArticleDataEle);
									log.getLogger('app').warn(err)
								}).catch(error => {
									log.getLogger('errors').error(error);
								})
							}
						}
					}
				}
				resolve(true);
			}, err => {
				reject(false);
				log.getLogger('errors').error(err);
			})

		});
	});
}

function scheduleCronstyle() {
	schedule.scheduleJob('30 30 21 * * *', () => {
		let pushCommentPromise = pushComment();
		let pushArticlePromise = pushArticle();
		Promise.all([pushCommentPromise, pushArticlePromise]).then(result => {
			log.getLogger('app').info('scheduleObjectLiteralSyntax:' + new Date())
		})
	})
}

scheduleCronstyle();